package arrays;

import java.util.ArrayList;

/**
 * 题目：顺时针打印二维数组
 * @Author Gavin
 * @date 2022.08.06 15:04
 */
public class array_21 {
    public ArrayList<Integer> solution(int[][] nums){
        ArrayList<Integer> result=new ArrayList<>();
        int r1 = 0, r2 = nums.length - 1, c1 = 0, c2 = nums[0].length - 1;
        while (r1<=r2&&c1<=c2){
            //先打印上面
            for (int i = c1; i <= c2; i++) {
                result.add(nums[r1][i]);
            }
            //打印右边
            for (int i = r1+1; i <= r2; i++) {
                result.add(nums[i][c2]);
            }

            //打印下边，需要注意，如果只有一行的话，打印下边就会重复，所以需要排除
            if(r1!=r2){
                for (int i = c2-1; i >r1 ; i--) {
                    result.add(nums[i][c1]);
                }
            }
            //打印左边
            if(c1!=c2){
                for (int i = r2-1; i >r1 ; i--) {
                    result.add(nums[c1][i]);
                }
            }
            r1++;
            r2--;
            c1++;
            c2--;
        }
        return result;
    }
}
